import java.util.ArrayList;
import java.util.List;

/**
 * @author LKQ
 * @date 2021/12/29 15:01
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] mat = {{1,2 }, {3, 4}};
        solution.matrixReshape2(mat, 1, 4);
    }

    public int[][] matrixReshape(int[][] mat, int r, int c) {
        int m = mat.length, n = mat[0].length;
        if (r * c != m * n) {
            return mat;
        }
        int[][] ans = new int[r][c];
        List<Integer> list = new ArrayList<>();
        for (int[] ints : mat) {
            for (int anInt : ints) {
                list.add(anInt);
            }
        }
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                ans[i][j] = list.get(i * c + j);
            }
        }
        return ans;
    }

    public int[][] matrixReshape2(int[][] mat, int r, int c) {
        // 不需要借助list
        int m = mat.length, n = mat[0].length;
        if (r * c != m * n) {
            return mat;
        }
        int[][] ans = new int[r][c];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int row = (i * n + j) / c, column = (i * n + j) % c;
                ans[row][column] = mat[i][j];
            }
        }
        return ans;
    }
}
